<template>
  <div class="user-info-page">
    <el-card class="info-card" shadow="hover">
      <el-tabs v-model="activeTab" class="user-tabs">
        <el-tab-pane label="基础资料" name="basic">
          <div class="user-info-content" v-loading="loading">
            <div class="info-item" v-if="userInfo.username">
              <span class="info-label">用户姓名</span>
              <span class="info-value">{{ userInfo.username }}</span>
            </div>
            <div class="info-item" v-if="userInfo.usernumber">
              <span class="info-label">工号</span>
              <span class="info-value">{{ userInfo.usernumber }}</span>
            </div>
            <div class="info-item" v-if="userInfo.accountname">
              <span class="info-label">用户名</span>
              <span class="info-value">{{ userInfo.accountname }}</span>
            </div>
            <div class="info-item" v-if="userInfo.usersex">
              <span class="info-label">性别</span>
              <span class="info-value">{{ userInfo.usersex }}</span>
            </div>
            <div class="info-item" v-if="userInfo.organname">
              <span class="info-label">组织</span>
              <span class="info-value">{{ userInfo.organname }}</span>
            </div>
            <div class="info-item" v-if="userInfo.jobname">
              <span class="info-label">岗位</span>
              <span class="info-value">{{ userInfo.jobname }}</span>
            </div>
            <div class="info-item" v-if="userInfo.phone !== undefined">
              <span class="info-label">手机号</span>
              <el-input 
                v-model="userInfo.phone" 
                placeholder="请输入手机号" 
                class="info-input"
                :disabled="!editing"
              />
            </div>
            <div class="info-item" v-if="userInfo.emails !== undefined">
              <span class="info-label">邮箱</span>
              <el-input 
                v-model="userInfo.emails" 
                placeholder="请输入邮箱" 
                class="info-input"
                :disabled="!editing"
              />
            </div>
            <div class="action-buttons" v-if="!editing">
              <el-button type="primary" @click="handleEdit">编辑</el-button>
            </div>
            <div class="action-buttons" v-else>
              <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
              <el-button @click="handleCancel">取消</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="修改密码" name="password">
          <div class="password-content">
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" :label-width="100">
              <el-form-item label="原密码" prop="oldPassword">
                <el-input 
                  v-model="passwordForm.oldPassword" 
                  type="password" 
                  placeholder="请输入原密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="新密码" prop="newPassword">
                <el-input 
                  v-model="passwordForm.newPassword" 
                  type="password" 
                  placeholder="请输入新密码"
                  show-password
                />
              </el-form-item>
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input 
                  v-model="passwordForm.confirmPassword" 
                  type="password" 
                  placeholder="请再次输入新密码"
                  show-password
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
                  修改密码
                </el-button>
                <el-button @click="handleResetPasswordForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import https from '@/Http/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface UserDto {
  id: number
  username: string
  usernumber: string
  accountname: string
  usersex: string
  phone: string
  emails: string
  organname: string
  jobname: string
  organid: number
  jobid: number
  roleid?: number
  status?: number
  pwd?: string
}


const loading = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const activeTab = ref('basic')
const editing = ref(false)
const passwordFormRef = ref<FormInstance>()

const userInfo = reactive<Partial<UserDto>>({})
const originalUserInfo = reactive<Partial<UserDto>>({})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T,>(payload: any): T => payload?.data ?? payload?.Data
const getPayloadMsg = (payload: any): string => payload?.msg ?? payload?.Msg ?? ''

// 获取用户信息
const fetchUserInfo = async () => {
  const userId = localStorage.getItem('userid')
  if (!userId) {
    ElMessage.error('未找到用户ID，请重新登录')
    return
  }

  loading.value = true
  try {
    const { data } = await https.Reads.get(`/RBAC/GetUserId`, {
      params: { userid: userId }
    })

    if (getStatusCode(data) === 1) {
      const userData = getPayloadData<UserDto>(data)
      Object.assign(userInfo, userData)
      Object.assign(originalUserInfo, { ...userData })
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取用户信息失败')
    }
  } catch (error: any) {
    console.error('获取用户信息失败:', error)
    ElMessage.error(error.response?.data?.msg || error.message || '获取用户信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 编辑
const handleEdit = () => {
  editing.value = true
}

// 取消编辑
const handleCancel = () => {
  editing.value = false
  Object.assign(userInfo, { ...originalUserInfo })
}

// 保存
const handleSave = async () => {
  saving.value = true
  try {
    // 调用更新用户信息的API，传递完整的用户信息
    const { data } = await https.Writes.put("/RBAC/UpdateUser", {
      id: userInfo.id,
      username: userInfo.username,
      usernumber: userInfo.usernumber,
      accountname: userInfo.accountname,
      usersex: userInfo.usersex,
      phone: userInfo.phone,
      emails: userInfo.emails,
      organid: userInfo.organid,
      jobid: userInfo.jobid,
      roleid: userInfo.roleid || 0,
      status: userInfo.status || 1,
      pwd: originalUserInfo.pwd || '' // 保持原密码不变
    })

    if (getStatusCode(data) === 1) {
      ElMessage.success('保存成功')
      Object.assign(originalUserInfo, { ...userInfo })
      editing.value = false
      // 重新获取用户信息以确保数据同步
      await fetchUserInfo()
    } else {
      ElMessage.error(getPayloadMsg(data) || '保存失败')
    }
  } catch (error: any) {
    console.error('保存失败:', error)
    ElMessage.error(error.response?.data?.msg || error.message || '保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    changingPassword.value = true

    const userId = localStorage.getItem('userid')
    if (!userId) {
      ElMessage.error('未找到用户ID，请重新登录')
      changingPassword.value = false
      return
    }

    // 调用修改密码的API
    const { data } = await https.Writes.put("/RBAC/UpdatePwd", {
      id: Number(userId),
      ypwd: passwordForm.oldPassword,
      pwds: passwordForm.newPassword
    })

    if (getStatusCode(data) === 1) {
      ElMessage.success(getPayloadMsg(data) || '密码修改成功')
      handleResetPasswordForm()
    } else {
      ElMessage.error(getPayloadMsg(data) || '密码修改失败')
    }
  } catch (error: any) {
    console.error('修改密码失败:', error)
    if (error.response?.data?.msg) {
      ElMessage.error(error.response.data.msg)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('修改密码失败，请稍后重试')
    }
  } finally {
    changingPassword.value = false
  }
}

// 重置密码表单
const handleResetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped lang="scss">
.user-info-page {
  padding: 20px;
  background: #f5f6f8;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.info-card {
  max-width: 800px;
  margin: 0 auto;
}

.user-tabs {
  :deep(.el-tabs__header) {
    margin-bottom: 30px;
  }

  :deep(.el-tabs__active-bar) {
    background-color: #409eff;
  }

  :deep(.el-tabs__item.is-active) {
    color: #409eff;
  }
}

.user-info-content {
  padding: 20px 0;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  min-height: 40px;
  line-height: 40px;

  .info-label {
    width: 120px;
    font-weight: 500;
    color: #333;
    flex-shrink: 0;
    text-align: left;
  }

  .info-value {
    flex: 1;
    color: #666;
    font-size: 14px;
  }

  .info-input {
    flex: 1;
    max-width: 300px;
  }
}

.action-buttons {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  gap: 12px;
}

.password-content {
  padding: 20px 0;
  max-width: 500px;
}
</style>

